package com.wmyg.antifake.fabric;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-12
 */
@Slf4j
@Repository
public class RabbitDao {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    MessagePropertiesConverter messagePropertiesConverter;

    public String sendFabricMessage(MqAdaptPo po) {
        String replyMessageContent = null;
        String correlationId = UUID.randomUUID().toString();
        Date sendTime = new Date();
        AMQP.BasicProperties props =
                new AMQP.BasicProperties("text/plain",
                        "UTF-8",
                        null,
                        2,
                        0, correlationId, "fabricReplyMessageExchange", null,
                        null, sendTime, null, null,
                        "FabricProducer", null);


        MessageProperties sendMessageProperties =
                messagePropertiesConverter.toMessageProperties(props, null,"UTF-8");
        sendMessageProperties.setReceivedExchange("fabricReplyMessageExchange");
        sendMessageProperties.setReceivedRoutingKey("fabricReplyMessage");
        sendMessageProperties.setRedelivered(true);
        try {
            String message = JSON.toJSONString(po);
            log.info("The message sent is {}", message);
            org.springframework.amqp.core.Message sendMessage = MessageBuilder.withBody(message.getBytes("UTF-8"))
                    .andProperties(sendMessageProperties)
                    .build();
            org.springframework.amqp.core.Message replyMessage = rabbitTemplate.sendAndReceive("fabricMessageExchange",
                    "fabricMessage", sendMessage);


            if (null == replyMessage) {
                log.error("The rabbit rpc is timeout");
                return null;
            }

            replyMessageContent = new String(replyMessage.getBody(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        return replyMessageContent;
    }

}
